<?php
namespace app\admin\model\publicuse\src;
class Curl
{
    protected $message = '';
    public function getMessage(){
        return $this->message;
    }
    public function http_requests(string $url,array $data = [],array $header= [],$method='POST'){
        $oCurl = curl_init();

        curl_setopt($oCurl,CURLOPT_URL,$url);

        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);

//关闭https验证

        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);

//        $data = json_encode( $data ,JSON_UNESCAPED_UNICODE );
        if(strtoupper($method)=="POST"){
//            echo 1;exit;
            curl_setopt($oCurl,CURLOPT_POST,true);
            curl_setopt($oCurl, CURLOPT_CUSTOMREQUEST, 'POST');
        }elseif (strtoupper($method)=="PUT"){
            curl_setopt($oCurl, CURLOPT_CUSTOMREQUEST, 'PUT');
        }elseif (strtoupper($method)=="DELETE"){
            curl_setopt($oCurl, CURLOPT_CUSTOMREQUEST, 'DELETE');
        }elseif (strtoupper($method)=="GET"){
            curl_setopt($oCurl, CURLOPT_CUSTOMREQUEST, 'GET');
            curl_setopt($oCurl,CURLOPT_POST,false);
        }
        if(!empty($data)){
            try{
                curl_setopt($oCurl,CURLOPT_POSTFIELDS,$data);
            }catch (Exception $e){
                try{
                    curl_setopt($oCurl,CURLOPT_POSTFIELDS,http_build_query($data));
                }catch (\Exception $e){
                    $data = json_encode( $data ,JSON_UNESCAPED_UNICODE );
                    curl_setopt($oCurl,CURLOPT_POSTFIELDS,$data);
                }
            }
//            curl_setopt($oCurl,CURLOPT_POSTFIELDS,$data);
        }
        if(empty($header)){
            curl_setopt($oCurl,CURLOPT_HEADER,false);
        }else{
            curl_setopt($oCurl,CURLOPT_HEADER,$header);
        }


//至关重要，CURLINFO_HEADER_OUT选项可以拿到请求头信息

        curl_setopt($oCurl, CURLINFO_HEADER_OUT, TRUE);

        $sContent = curl_exec($oCurl);
//通过curl_getinfo()可以得到请求头的信息

        $a=curl_getinfo($oCurl);
        if($error=curl_errno($oCurl)){
            $this->message = $error;
        }
        return $sContent;
    }
}